package com.blb.dslock_demo.redis;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.blb.dslock_demo.zk.Product;
import com.blb.dslock_demo.zk.ProductMapper;
import com.blb.dslock_demo.zk.ProductService;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Service
public class ProductServiceRedisImpl extends ServiceImpl<ProductMapper,Product> implements ProductService {

    @Resource
    private RedissonClient redissonClient;

    @Resource
    private ProductMapper productMapper;

    @Override
    public void reduceStock(Long productId) throws Exception {
        //获得redisson分布式锁
        RLock mylock = redissonClient.getLock("mylock");
        try {
            //请求锁
            //第一个参数100s表示尝试获取分布式锁，并且最大的等待获取锁的时间为100s
            //第二个参数10s表示上锁之后，10s内操作完毕将自动释放锁
            if(mylock.tryLock(100,10, TimeUnit.SECONDS)){
                //查询库存
                Product product = productMapper.selectById(productId);
                if(product.getStock() > 0){
                    //扣库存
                    product.setStock(product.getStock() - 1);
                    productMapper.updateById(product);
                    System.out.println("扣库存成功");
                }else {
                    System.out.println("库存不足");
                }
            }else{
                System.out.println("获得锁失败，等待");
            }
        } finally {
            //释放锁
            mylock.unlock();
        }
    }
}
